import React, {Component} from 'react';
import $ from "jquery";

interface props {
    onRef: any;
}

/**验证码*/
class Captcha extends Component<props, any> {
    private canvas: any;

    constructor(props: props) {
        super(props)
        this.state = {
            code: '',
            codeLength: 4,
            fontSizeMin: 20,
            fontSizeMax: 25,
            backgroundColorMin: 240,
            backgroundColorMax: 250,
            colorMin: 10,
            colorMax: 20,
            lineColorMin: 75,
            lineColorMax: 240,
            contentWidth: 251,
            contentHeight: 75,
            showError: false, // 默认不显示验证码的错误信息,
            height: 50,
            width: 350,
        }
        this.canvas = React.createRef();
    }

    componentDidMount() {
        const parent = $("#parent");
        this.setState({width: parent.width(), height: parent.height()});
        const code = $("#captcha-btn");
        if (parent && code) {
            code.css("height", parent.height());
        }
        this.props.onRef(this);
        this.drawPic()
    }

    /* shouldComponentUpdate(nextProps: Readonly<any>, nextState: Readonly<any>, nextContext: any): boolean {
         return false;
     }*/

    // 生成一个随机数
    // eslint-disable-next-line arrow-body-style
    randomNum = (min: any, max: any) => {
        return Math.floor(Math.random() * (max - min) + min)
    }

    drawPic = () => {
        this.randomCode()
    }

    // 生成一个随机的颜色
    // eslint-disable-next-line react/sort-comp
    randomColor(min: any, max: any) {
        const r = this.randomNum(min, max)
        const g = this.randomNum(min, max)
        const b = this.randomNum(min, max)
        return `rgb(${r}, ${g}, ${b})`
    }

    drawText(ctx: any, txt: any, i: any) {
        ctx.fillStyle = this.randomColor(this.state.colorMin, this.state.colorMax)
        const fontSize = this.randomNum(this.state.fontSizeMin, this.state.fontSizeMax)
        ctx.font = fontSize + 'px SimHei'
        const padding = 10;
        const offset = (this.state.width - 40) / (this.state.code.length - 1)
        let x = padding;
        if (i > 0) {
            x = padding + (i * offset)
        }
        let y = this.randomNum(this.state.fontSizeMax, this.state.height - 5)
        if (fontSize > 40) {
            y = 40
        }
        const deg = this.randomNum(-10, 10)
        // 修改坐标原点和旋转角度
        ctx.translate(x, y)
        ctx.rotate(deg * Math.PI / 180)
        ctx.fillText(txt, 0, 0)
        // 恢复坐标原点和旋转角度
        ctx.rotate(-deg * Math.PI / 180)
        ctx.translate(-x, -y)
    }

    drawLine(ctx: any) {
        // 绘制干扰线
        for (let i = 0; i < 1; i++) {
            ctx.strokeStyle = this.randomColor(this.state.lineColorMin, this.state.lineColorMax)
            ctx.beginPath()
            ctx.moveTo(this.randomNum(0, this.state.width), this.randomNum(0, this.state.height))
            ctx.lineTo(this.randomNum(0, this.state.width), this.randomNum(0, this.state.height))
            ctx.stroke()
        }
    }

    drawDot(ctx: any) {
        // 绘制干扰点
        for (let i = 0; i < 100; i++) {
            ctx.fillStyle = this.randomColor(0, 255)
            ctx.beginPath()
            ctx.arc(this.randomNum(0, this.state.width), this.randomNum(0, this.state.height), 1, 0, 2 * Math.PI)
            ctx.fill()
        }
    }

    //重画验证码
    reloadPic = () => {
        this.drawPic()
        /* this.props.form.setFieldsValue({
             sendcode: '',
         });*/
    }

    // 输入验证码
    changeCode = (e: any) => {
        if (e.target.value.toLowerCase() !== '' && e.target.value.toLowerCase() !== this.state.code.toLowerCase()) {
            this.setState({
                showError: true
            })
        } else if (e.target.value.toLowerCase() === '') {
            this.setState({
                showError: false
            })
        } else if (e.target.value.toLowerCase() === this.state.code.toLowerCase()) {
            this.setState({
                showError: false
            })
        }
    }
    //检查验证码是否正确
    CheckCode = (e: string) => {
        if (e.toLowerCase() !== '' && e.toLowerCase() !== this.state.code.toLowerCase()) {
            return false;
        } else if (e.toLowerCase() === '') {
            return false;
        } else if (e.toLowerCase() === this.state.code.toLowerCase()) {
            return true;
        }
    }

    // 随机生成验证码
    randomCode() {
        let random = ''
        //去掉iIl0oO
        const str = 'QWERTYUPLKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm123456789'
        for (let i = 0; i < this.state.codeLength; i++) {
            const index = Math.floor(Math.random() * 51);
            random += str[index];
        }
        this.setState({
            code: random
        }, () => {
            const canvas = this.canvas.current;
            const ctx = canvas.getContext('2d')
            ctx.textBaseline = 'bottom'
            // 绘制背景
            ctx.fillStyle = this.randomColor(this.state.backgroundColorMin, this.state.backgroundColorMax)
            ctx.fillRect(0, 0, this.state.width, this.state.height)
            // 绘制文字
            for (let i = 0; i < this.state.code.length; i++) {
                this.drawText(ctx, this.state.code[i], i)
            }
            this.drawLine(ctx)
            this.drawDot(ctx)
        });
    }

    render() {
        return (
            <div id={"parent"} style={{float: "left", width: "55%", height: "100%"}}>
                <canvas
                    // onClick={this.reloadPic}
                    ref={this.canvas}
                    width={this.state.width}
                    height={this.state.height}>
                </canvas>
            </div>
        );
    }
}

export default Captcha;